<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>peerA</title>
</head>
<body>
<video id="localVideo"></video>
<video id="remoteVideo" autoplay></video>
<br>
<button type="button" onclick="call()">呼叫</button>
<button type="button" onclick="hangup()">挂断</button>

</body>
<script type="text/javascript">
	let stream, wsKey
	let localStream, peerConnA, peerConnB

	// peer池
	let peerListObject = {}

	var ws = new WebSocket('ws://172.16.200.188:3030');

	ws.onopen = function(evt) {
		console.log('Connection open ...');
	};

	ws.onmessage = function(evt) {

		let tempData = JSON.parse(evt.data)

		switch (tempData.type){
			case 'backAnswer':
				pcaSetRemote(tempData.data, tempData.key)
				break
			case 'candidateToA':
				candidateToA(tempData.data, tempData.key)
				break
			case 'mainSendOffer':
				sendOffer(tempData.data)
				break
			case "backKey":
				wsKey = tempData.data
				break
		}

	};

	ws.onclose = function(evt) {
		console.log('Connection closed.');
	};

	async function pcaSetRemote(data, key){
		try{
			await peerListObject[key].setRemoteDescription(data)
		}catch (e) {
			console.log(e)
		}
	}

	async function sendOffer(data){

		// 视频轨道

		// 音频轨道

		let configuration = {"iceServer": [{"url": "stun: stun.l.google.com:19302"}]}

		// 一对一
		peerConnA = new RTCPeerConnection(configuration)

		//一对多
		// peerListObject[data] = new RTCPeerConnection(configuration)
		peerListObject[data] = peerConnA
		peerConnA.addEventListener('icecandidate', onIceCandidDateA)
		peerConnA.addEventListener('iceconnectionstatechange', onIceStateChangeA)

		// A 将流添加至 peerConnA
		localStream.getTracks().forEach(track => {
			peerConnA.addTrack(track, localStream)
		})

		try{
			const offer = await peerConnA.createOffer()
			await onCreateOfferSuccess(offer)
		}catch (e) {
		}

	}

	async function onCreateOfferSuccess(desc){
		try{
			// 设置本地描述
			await peerConnA.setLocalDescription(desc)
			onSetLocalSuccess(peerConnA)

			let obj = JSON.stringify({
				type: 'createOffer',
				data: desc
			})

			ws.send(obj);

		}catch (e) {
		}



	}

	function onSetLocalSuccess(pc){

	}

	async function onIceCandidDateA(evt){

		try{
			if(evt.candidate){

				let candObj = JSON.stringify({
					type: 'candidateToB',
					data: evt.candidate
				})

				ws.send(candObj)
			}

		}catch (e){console.log(e)}
	}

	async function candidateToA(data, key){
		try{
			await peerListObject[key].addIceCandidate(data)
			onAddIceCandidateSuccess(peerConnA)
		}catch (e){}
	}



	function onAddIceCandidateSuccess(pc){

	}

	function onIceStateChangeA(evt){

	}

	function hangup(){
		peerConnA.close()
		peerConnB.close()
		peerConnA = null
		peerConnB = null
	}

	function initStream() {
		navigator.mediaDevices.getUserMedia({
			video: true,
			audio: true
		}).then(res => {
			stream = res
			localVideo.srcObject = stream
			localStream = stream
			localVideo.play()
			delVideoTrack()
		}).catch(err => console.log(err))
	}
	initStream()


	// 删除音频轨道，本地调试防止杂音
	function delVideoTrack(){
		console.log('delVideoTrack')
		stream.removeTrack(stream.getAudioTracks()[0])
	}
</script>
</html>
